package com.woniuxy.portal.config;

import com.woniuxy.common.RedisConst;
import com.woniuxy.portal.model.entity.Book;
import com.woniuxy.portal.service.BookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 数据预热，初始化Redis中库存
 */
@Component
@Slf4j
public class StorageRunner implements CommandLineRunner {

    //访问数据库
    @Autowired
    private BookService bookService;

    //使用Redis
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void run(String... args) throws Exception {
        //判断是否已经初始化
        if (!redisTemplate.hasKey(RedisConst.BOOK_STORAGE)) {
            //从数据库中获取所有书籍的库存信息
            List<Book> books = bookService.list();
            //存入Redis
            books.forEach(book -> {
                //获取操作Hash数据的对象
                HashOperations ops = redisTemplate.opsForHash();
                //键 字段(书籍ID) 值(库存)
                ops.put(RedisConst.BOOK_STORAGE, book.getId().toString(), book.getStoreCount());
            });
            log.info("库存数据初始化成功");
        }
    }
}